import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入views文件里的login/register文件
import Register from '@/views/Register'
import Login from '@/views/Login'
import Main from '@/views/Main'
// 子组件
import Home from '@/views/Menus/Home'
import UserInfo from '@/views/Menus/User'
import UserPhoto from '@/views/Menus/User/userPhoto.vue'
import UserPassword from '@/views/Menus/User/userPassword.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
import ArtList from '@/views/Menus/Article/ArtList.vue'
// 导入store里的token值
import store from '@/store/index'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserPhoto
      }, {
        path: 'user-pwd',
        component: UserPassword
      }, {
        path: 'art-cate',
        component: ArtCate
      }, {
        path: 'art-list',
        component: ArtList
      }
    ]
  },
  { path: '/register', component: Register },
  { path: '/login', component: Login }// 登入页面路由规则
]

const router = new VueRouter({
  routes
})
// 全局拦截守卫是为了判断有无token值能否跳转
router.beforeEach((to, from, next) => {
  // 1.登入（/login)和注册(/register)页面，不需要访问权限，直接放行
  // 2.除此之外，其他路由地址，有需要访问权限
  // 3.从vuex中获取token的值，并判断是否有token
  // 3.1如果有token，认为用户已经登入了，直接放行
  // 3.2如果没有token，认为用户没有登入，则强制跳转到登入页面
  if (to.path === '/login' || to.path === '/register') {
    // 去往登入页和注册页直接放行
    next()
  } else {
    if (store.state.token) {
      next()// 如果token有值，放行
    } else {
      // 如果token没有值跳转到登录页
      next('/login')
    }
  }
})

export default router
